import { instance } from '@/utils/request'
import { useIntervalFn } from '@vueuse/core'
import { ElMessageBox, ElNotification } from 'element-plus'
import { defineStore } from 'pinia'
import { reactive, ref } from 'vue'

export const useTaskStore = defineStore('task', () => {
  const taskList = ref([])

  const taskListPaging = reactive({
    total: 0,
    currentPage: 1,
    pageSize: 20,
  })

  const { resume: getTaskList } = useIntervalFn(
    async (params?: object) => {
      const { data } = await instance({
        url: `/dc-task/v1/list`,
        method: 'get',
        params: {
          limit: taskListPaging.pageSize,
          page: taskListPaging.currentPage,
          ...params,
        },
      })
      const { list = [], total = 0 } = data || {}
      taskList.value = list
      taskListPaging.total = total
    },
    import.meta.env.VITE_INTERVAL_TIME,
    { immediateCallback: true },
  )

  const cancelTask = async (id) => {
    await ElMessageBox.confirm('请确认是否终止该任务 ', '警告')
    await instance({
      url: `/dc-task/v1/update`,
      method: 'put',
      data: { id, status: 4 },
    })
    getTaskList()
    ElNotification({ type: 'success', title: '终止任务成功' })
  }

  return {
    cancelTask,
    getTaskList,
    taskList,
    taskListPaging,
  }
})
